# PowerShell脚本：检查IP是否可用并保存结果

# 文件路径
$excelFile = "c:\Users\Administrator\Desktop\ip_pool\ip_detail.xlsx"
$outputFile = "c:\Users\Administrator\Desktop\ip_pool\available_ips.csv"

Write-Host "开始IP可用性检查"
Write-Host "输入文件: $excelFile"

# 检查文件是否存在
if (-not (Test-Path $excelFile)) {
    Write-Host "错误: 输入文件不存在"
    exit 1
}

# 使用Import-Excel模块读取Excel文件
# 如果没有安装，尝试安装
if (-not (Get-Module -ListAvailable -Name ImportExcel)) {
    Write-Host "安装ImportExcel模块..."
    Install-Module -Name ImportExcel -Scope CurrentUser -Force -AllowClobber
}

try {
    # 读取Excel文件
    Write-Host "正在读取Excel文件..."
    $data = Import-Excel -Path $excelFile
    Write-Host "成功读取Excel文件"
    Write-Host "总行数: $($data.Count)"
    
    # 获取第一列的名称
    $firstColumn = $data[0].PSObject.Properties.Name[0]
    Write-Host "使用列: $firstColumn"
    
    # 提取IP地址
    $ipList = $data | Select-Object -ExpandProperty $firstColumn | Where-Object { $_ -ne $null } | ForEach-Object { $_.ToString().Trim() }
    Write-Host "提取到 $($ipList.Count) 个IP地址"
    
    # 检查IP可用性
    $availableIPs = @()
    $total = $ipList.Count
    
    for ($i = 0; $i -lt $total; $i++) {
        $ip = $ipList[$i]
        Write-Host "\n检查 IP $($i+1)/$total: $ip"
        
        # 验证IP格式
        if ($ip -notmatch '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') {
            Write-Host "  跳过: 无效的IP格式"
            continue
        }
        
        $isAvailable = $false
        $maxRetries = 2
        
        for ($retry = 0; $retry -lt $maxRetries; $retry++) {
            try {
                Write-Host "  尝试 $($retry+1)/$maxRetries..."
                
                # 创建代理对象
                $proxy = New-Object System.Net.WebProxy -ArgumentList "http://$ip"
                $client = New-Object System.Net.WebClient
                $client.Proxy = $proxy
                $client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                $client.Timeout = 5000  # 5秒超时
                
                # 发送请求
                $response = $client.DownloadString("https://www.baidu.com")
                
                # 如果成功获取内容，认为IP可用
                Write-Host "  ✓ 成功: IP可用"
                $isAvailable = $true
                break
                
            } catch {
                Write-Host "  ✗ 失败: $($_.Exception.Message)"
                if ($retry -lt ($maxRetries - 1)) {
                    Write-Host "  等待1秒后重试..."
                    Start-Sleep -Seconds 1
                }
            }
        }
        
        if ($isAvailable) {
            $availableIPs += $ip
            Write-Host "  IP已添加到可用列表"
        }
    }
    
    # 保存可用IP
    Write-Host "\n检查完成!"
    Write-Host "可用IP数量: $($availableIPs.Count)"
    
    if ($availableIPs.Count -gt 0) {
        Write-Host "保存可用IP到CSV文件..."
        
        # 创建结果对象
        $results = @()
        foreach ($ip in $availableIPs) {
            $results += [PSCustomObject]@{Available_IP = $ip}
        }
        
        # 导出到CSV
        $results | Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8
        Write-Host "✓ 可用IP已保存到: $outputFile"
        
        # 显示保存的结果
        Write-Host "\n保存的可用IP:
$($availableIPs -join "\n")"
    } else {
        Write-Host "没有找到可用的IP地址"
    }
    
} catch {
    Write-Host "发生错误: $($_.Exception.Message)"
    Write-Host $_.Exception.StackTrace
}